<template>
  <div>
    <div class="screen-header">
      <button class="back-btn" @click="goBack">
        <i class="fas fa-arrow-left"></i> 返回
      </button>
      <div class="screen-title">
        <i class="fas fa-file-upload"></i>
        <span>文件存件</span>
      </div>
      <div></div> <!-- 占位元素 -->
    </div>
    
    <div class="form-group">
      <label>请扫描或输入存件码</label>
      <div class="input-group">
        <input 
          type="text" 
          class="form-control" 
          placeholder="请输入存件码" 
          v-model="depositCode"
          @keyup.enter="validateDepositCode"
        >
                        <button 
                          class="btn" 
                          :class="{ 'btn-disabled': !isLoggedIn }"
                          @click="validateDepositCode" 
                          :disabled="loading || !isLoggedIn"
                          :title="!isLoggedIn ? '请先登录' : ''"
                        >
                          <i v-if="loading" class="fas fa-spinner fa-spin"></i>
                          <i v-else-if="!isLoggedIn" class="fas fa-lock"></i>
                          {{ loading ? '验证中...' : (!isLoggedIn ? '请先登录' : '验证') }}
                        </button>
      </div>
    </div>
    
    <div class="qr-scanner">
      <div class="scanner-header">
        <button 
          class="btn btn-login" 
          @click="handleLoginButtonClick"
        >
          <i :class="isLoggedIn ? 'fas fa-sign-out-alt' : 'fas fa-user'"></i>
          {{ isLoggedIn ? '登出' : '登录' }}
        </button>
        <h3>或扫描二维码</h3>
      </div>
      <div class="qr-placeholder">
        <i class="fas fa-qrcode"></i>
        <p>请将存件二维码对准扫描区</p>
      </div>
      <button class="btn btn-block" style="margin-top: 15px;">启动摄像头扫描</button>
    </div>
    
    <div v-if="showSuccess" class="deposit-success">
      <div class="success-screen">
        <div class="success-icon">
          <i class="fas fa-check-circle"></i>
        </div>
        <div class="success-message">
          存件码验证成功！
        </div>
        
                        <div class="info-card" v-if="storageDetail">
                            <div class="info-row">
                                <span>存件码</span>
                                <span>{{ storageDetail.code }}</span>
                            </div>
                            <div class="info-row">
                                <span>存件名称</span>
                                <span>{{ storageDetail.name }}</span>
                            </div>
                            <div class="info-row">
                                <span>存件描述</span>
                                <span>{{ storageDetail.description }}</span>
                            </div>
                            <div class="info-row">
                                <span>负责老师</span>
                                <span>{{ storageDetail.teacherName }}</span>
                            </div>
                            <div class="info-row">
                                <span>存件状态</span>
                                <span>{{ getStatusText(storageDetail.status) }}</span>
                            </div>
                            <div class="info-row">
                                <span>创建时间</span>
                                <span>{{ storageDetail.createTime }}</span>
                            </div>
                            <div class="info-row">
                                <span>有效期至</span>
                                <span>{{ storageDetail.expireTime }}</span>
                            </div>
                        </div>
        
        <div class="countdown" v-if="countdown > 0">
          请于 <span>{{ countdown }}</span> 秒内完成存件
        </div>
        
        <button class="btn btn-success btn-block" @click="completeDeposit">完成存件</button>
      </div>
    </div>
    
    <!-- 登录弹窗 -->
    <LoginModal 
      v-model:visible="loginModalVisible" 
      @login="handleLogin"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import LoginModal from '../components/LoginModal.vue'
import { getPickupStorageDetail, completeStorageByCode } from '../api'
import type { StorageDetailResponseData } from '../api'
import { checkLoginStatus, logout, isLoggedIn } from '../stores/auth'

const router = useRouter()

// 响应式数据
const depositCode = ref('')
const showSuccess = ref(false)
const countdown = ref(0)
const loginModalVisible = ref(false)
const storageDetail = ref<StorageDetailResponseData | null>(null)
const loading = ref(false)

// 验证存件码
const validateDepositCode = async () => {
  // 检查登录状态
  if (!isLoggedIn.value) {
    alert('请先登录后再进行存件验证')
    return
  }
  
  if (depositCode.value.trim() === '') {
    alert('请输入存件码')
    return
  }
  
  loading.value = true
  
  try {
    // 调用存件详情接口，使用存件码进行验证
    const response = await getPickupStorageDetail(depositCode.value)
    
    // 保存存件详情数据
    storageDetail.value = response.data
    
    // 显示成功界面
    showSuccess.value = true
    
    
    // 开始倒计时
    startCountdown()
    
  } catch (error: any) {
    console.error('获取存件详情失败:', error)
    alert(error.message || '存件码验证失败，请检查存件码是否正确')
  } finally {
    loading.value = false
  }
}

// 倒计时函数
const startCountdown = () => {
  countdown.value = 30
  
  const timer = setInterval(() => {
    countdown.value--
    
    if (countdown.value <= 0) {
      clearInterval(timer)
      alert('存件超时，请重新操作')
      showSuccess.value = false
      countdown.value = 0
    }
  }, 1000)
}

// 完成存件
const completeDeposit = async () => {
  if (!storageDetail.value) {
    alert('存件信息不存在，请重新验证存件码')
    return
  }

  if (!depositCode.value.trim()) {
    alert('存件码不存在，请重新验证存件码')
    return
  }

  try {
    // 调用完成存件接口
    const response = await completeStorageByCode(depositCode.value)
    
    console.log('完成存件成功:', response.data)
    
    // 跳转到完成页面
    router.push({
      path: '/complete',
      query: {
        type: 'deposit',
        message: '存件完成！',
        details: `您的文件已成功存入${response.data.cabinetName || '柜子'}${response.data.location ? ` (${response.data.location})` : ''}，请妥善保管取件码。`,
        storageCode: response.data.code,
        storageId: response.data.id?.toString() || '',
        status: response.data.status.toString()
      }
    })
    
  } catch (error: any) {
    console.error('完成存件失败:', error)
    alert(error.message || '完成存件失败，请重试')
  }
}

// 返回上一页
const goBack = () => {
  router.push('/')
}

// 处理登录按钮点击
const handleLoginButtonClick = () => {
  console.log('登录按钮被点击')
  console.log('当前登录状态:', isLoggedIn.value)
  if (isLoggedIn.value) {
    handleLogout()
  } else {
    showLoginModal()
  }
}

// 显示登录弹窗
const showLoginModal = () => {
  console.log('showLoginModal 被调用')
  console.log('当前登录状态:', isLoggedIn.value)
  loginModalVisible.value = true
  console.log('loginModalVisible 设置为:', loginModalVisible.value)
}

// 处理登录
const handleLogin = (loginData: { username: string; password: string }) => {
  console.log('登录信息:', loginData)
  // 这里可以调用登录API
  // 登录成功后可以进行相关操作
}

// 获取状态文本
const getStatusText = (status: number): string => {
  const statusMap: Record<number, string> = {
    0: '未存件',
    1: '已存件',
    2: '已取件',
    3: '已过期'
  }
  return statusMap[status] || '未知状态'
}

// 处理登出
const handleLogout = () => {
  if (confirm('确定要退出登录吗？')) {
    logout()
    alert('已退出登录')
  }
}

// 初始化登录状态
onMounted(() => {
  checkLoginStatus()
})
</script>

<style scoped>
.screen-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #4a6572;
}

.screen-title {
  font-size: 1.8rem;
  display: flex;
  align-items: center;
  gap: 10px;
}

.back-btn {
  background: none;
  border: none;
  color: white;
  font-size: 1.2rem;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
}

.form-group {
  margin-bottom: 25px;
}

.form-group label {
  display: block;
  margin-bottom: 10px;
  font-size: 1.2rem;
}

.input-group {
  display: flex;
  gap: 10px;
}

.form-control {
  flex: 1;
  padding: 15px;
  border: none;
  border-radius: var(--border-radius);
  font-size: 1.2rem;
  background-color: #4a6572;
  color: white;
}

.form-control::placeholder {
  color: #bdc3c7;
}

.btn {
  padding: 15px 25px;
  background-color: var(--primary);
  color: white;
  border: none;
  border-radius: var(--border-radius);
  font-size: 1.2rem;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn:hover:not(:disabled) {
  background-color: #2980b9;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-disabled {
  background-color: #6c757d !important;
  cursor: not-allowed;
}

.btn-disabled:hover {
  background-color: #6c757d !important;
}

.btn-block {
  width: 100%;
}

.btn-success {
  background-color: var(--secondary);
}

.btn-success:hover {
  background-color: #27ae60;
}

.qr-scanner {
  text-align: center;
  padding: 30px;
  background-color: #1a252f;
  border-radius: var(--border-radius);
  margin: 20px 0;
}

.scanner-header {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
  margin-bottom: 20px;
}

.scanner-header h3 {
  margin: 0;
  color: white;
}

.btn-login {
  background-color: var(--warning);
  color: white;
  padding: 10px 20px;
  font-size: 1rem;
}

.btn-login:hover {
  background-color: #d35400;
}

.qr-placeholder {
  width: 250px;
  height: 250px;
  background-color: #2c3e50;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: var(--border-radius);
  color: #bdc3c7;
  flex-direction: column;
  gap: 15px;
}

.qr-placeholder i {
  font-size: 4rem;
}

.success-screen {
  text-align: center;
  padding: 40px 20px;
}

.success-icon {
  font-size: 5rem;
  color: var(--secondary);
  margin-bottom: 20px;
}

.success-message {
  font-size: 1.8rem;
  margin-bottom: 30px;
}

.info-card {
  background-color: #4a6572;
  border-radius: var(--border-radius);
  padding: 20px;
  margin-bottom: 20px;
}

.info-row {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 1px solid #5d6d7e;
}

.info-row:last-child {
  border-bottom: none;
}


.countdown {
  font-size: 1.5rem;
  text-align: center;
  margin: 20px 0;
  color: var(--warning);
}

.fa-spinner {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style>
